use std::fmt::format;
use std::fs;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};

fn main() {
    // println!("Hello, world!");


    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();


    for stream in listener.incoming() {
        let mut stream = stream.unwrap();
        
        handle_connect(&mut stream);

    }
}


fn handle_connect(stream: &mut TcpStream) {
    let mut buffer = [0; 512];


    stream.read_exact(&mut buffer).unwrap();

    println!("Request : {}", String::from_utf8_lossy(&buffer));


    let get = b"GET / HTTP/1.1\r\n";


    let (status, filename) = if buffer.starts_with(get) {
        ("HTTP/1.1 200 OK \r\n\r\n", "hello.html")
    } else {
        ("HTTP/1.1 404  Not Found \r\n\r\n", "404.html")
    };


    let content = fs::read_to_string(filename).unwrap();
    let resp = format!("{}{}", status, content);

    stream.write(resp.as_bytes()).unwrap();

    stream.flush().unwrap();
}
